import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link ,browserHistory} from 'react-router';
import request from 'superagent';
import api from '../api';
import {bind_change} from '../common/State';

import {  Modal,Icon,message,Table,Dropdown,Menu,Row,Col,Button,Input,InputNumber,Form ,Select,Switch,Upload} from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
const Option = Select.Option;
const InputGroup = Input.Group;

//导入常量
import {BANNER_POSITION} from '../constants/index';

class BannerEdit extends React.Component {
  constructor(props, context){
      super(props, context);
      let {id} = props.location.query||{};
      this.state={
        banner:{
          id
        }
      };
  }

  componentWillMount(){
    let {banner} = this.state;
    if(banner.id){
      this.doFetch(banner.id);
    }else{
      this.doFetchPosition(1);
    }
  }

  componentDidMount(){
  
  }

  //通过ID查询
  async doFetch(id){
    let result = await api('/operation/banner/get',{id});
    if(result.cd!=0){
      message.error(result.msg);
      return
    }
    this.setState({
      banner:result.data
    })
  }

  //查询排序编号
  async doFetchPosition(type){
    let {banner} = this.state;
    let result = await api('/operation/banner/getPosition',{type});
    if(result.cd==0){
      banner.position = result.data;
      this.setState({
        banner
      })
    }
  }

  //上传
  onDrop =  (e,z) => {
    var file = e.file;
    message.loading("正在上传...",0);
    var req = request.post('/file/upload-image');
    req.attach(file.name, file);
    req.end((err,rsq)=>{
      message.destroy();
        if(err){
             message.error("上传失败");
        } else {
            if(err){
                message.error(this,"上传失败！");
            }else{
              message.success('上传成功')
              if(rsq.text){
                let {banner} = this.state;
                banner.save_url = rsq.text;
                this.setState({banner})
              }
                
            }
        }
    });
  }

  //保存事件
  btnSaveClick(event){
      const {validateFieldsAndScroll } = this.props.form;
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          return
        }
        this.save(values)
      })
  }
  //保存请求
  async save(values){
      let {banner} = this.state;
      values.save_url = banner.save_url;
      let params = Object.assign(banner,values);
      params.status = params.status==true?'1':'2';

      let result = await api('/operation/banner/save',{banner});
      if(result.cd!=0){
        message.error(result.msg);
        return;
      }
      message.success('保存成功',1,() => {
        this.context.router.push('/operation/banner/list')
      });

  }

  render() {
    const { getFieldDecorator} = this.props.form;
    let {banner} = this.state;
    return (
        <div>
            <NavBar navs={[
              {title:'banner管理',href:'/operation/banner/list'},
              {title:(banner.id?'编辑':'创建')+`新banner`}
            ]} />
            <ContentBody className='container'> 
                <h2>banner基本信息</h2>
                <div className='height20'></div>
                <form>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item 
                            label="banner名称"
                          >
                            {getFieldDecorator('title', {
                              rules: [
                                {
                                  required: true,
                                  message: 'banner名称',
                                },
                              ],
                              initialValue:banner.title||""
                            })(<Input
                                  placeholder="banner名称"
                                />
                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item 
                            label="banner链接地址"
                          >
                            {getFieldDecorator('link_url', {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入banner链接地址',
                                },
                              ],
                              initialValue:banner.link_url||""
                            })(<Input size="large"  placeholder="请输入banner链接地址" />)}
                          </Form.Item>
                      </Col >
                    </Row>
                    <Row gutter={30}>
                      <Col span={12}>
                        <Form.Item 
                            label="图片（尺寸为640*400）"
                          >
                            {getFieldDecorator('save_url', {
                              rules: [
                                {
                                  required: true,
                                  message: '请输入banner链接地址',
                                },
                              ],
                              initialValue:banner.save_url||""
                            })(
                              <Upload
                                style={{marginTop:'10px'}}
                                className="avatar-uploader"
                                name="avatar"
                                showUploadList={false}
                                accept="image/png,image/jpg,image/jpeg"
                                customRequest={this.onDrop.bind(this)}
                              >
                                {
                                  banner.save_url?
                                  <img src={banner.save_url} className="avatar" />
                                  :<Icon type="plus" className="avatar-uploader-trigger" />
                                }
                              </Upload>
                            )}
                          </Form.Item>
                      </Col >
                    </Row>
                    <div className='height30'></div>
                    <h2>banner显示设置</h2>
                    <div className='height10'></div>
                    <Row gutter={30}>
                      <Col span={12}>
                          <Form.Item 
                            label="banner位置"
                          >
                            {getFieldDecorator('type', {
                              rules: [
                                {
                                  required: true,
                                  message: '请选择banner位置',
                                },
                              ],
                              initialValue:banner.type?(banner.type+""):'1'
                            })(
                                <Select
                                  showSearch
                                  style={{ width: '100%' }}
                                  placeholder='请选择banner位置'
                                  onChange = {(value) => {
                                    if(!banner.id){
                                      this.doFetchPosition(value);
                                    }
                                     
                                  }}
                                >
                                  {
                                    Object.keys(BANNER_POSITION).map((key,index) => {
                                      return (
                                        <Option key={index} value={key} >{BANNER_POSITION[key]}</Option>
                                      )
                                    })
                                  }
                                </Select>
                              
                            )}
                          </Form.Item>
                      </Col >
                      <Col span={12}>
                          <Form.Item 
                            label="banner排序"
                          >
                            {getFieldDecorator('position', {
                              rules: [
                                {
                                  required: false,
                                  message: '请输入banner排序',
                                },
                              ],
                              initialValue:banner.position||""
                            })(<Input size='large' placeholder='请输入banner排序'/>)}
                          </Form.Item>
                      </Col >
                    </Row>
                    
                    <Row gutter={30}>
                      <Col span={12}>
                        <label >是否开启:</label>
                        <Switch 
                          checkedChildren={'开'} 
                          unCheckedChildren={'关'}
                          checked={banner.status==1?true:false} 
                          onChange={(checked)=>{
                            banner.status = checked;
                            this.setState({banner});
                          }}
                        />
                      </Col >
                      
                    </Row>
                </form>
               
                <div className="text-center ">
                    <Button  
                      type='primary'
                      onClick={this.btnSaveClick.bind(this)}
                    >
                      保存
                    </Button>
                    <Button  
                      type='default'
                      style={{marginLeft:"20px"}} 
                      onClick={()=>{this.context.router.push('/operation/banner/list')}}
                    >
                      返回
                    </Button>
                 </div>
            </ContentBody>
            
        </div>
    );
  }
}
BannerEdit.contextTypes= { router: React.PropTypes.object.isRequired};

export default Form.create()(BannerEdit);
